<?php

namespace App\Http\Controllers\Api\Wap;

use App\Http\Controllers\Common\ApiController;
use App\Models\Article\ArticleInfo;
use App\Models\Article\ArticleOrder;
use App\Models\Constant\Constant;
use App\Models\Setting\SysSetting;
use App\Models\User\MemberOrder;
use App\Models\User\User;
use EasyWeChat\Factory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\Rule;

class IndexController extends ApiController {

    public function buyMember(Request $request) {
        $type = $request->input('type');

        $this->validate($request, [
            'type'=>['required',Rule::in(['first','month','quarter','year'])]
        ],[],[
            'type'=>'会员类型错误！'
        ]);

        $token = $request->header('token');
        $id = checkJWT($token)['id'];
        $user = User::where(compact('id'))->first();
        if(empty($user)) return responseFail('无效用户');

        if($type=='first' && $user->isBuyFirst()) {
            return responseFail('您已经购买过首试了！');
        }
        $order_number = time().uniqid();
        $price = SysSetting::where('key',$type)->first()->val??138;
        $fee = env('APP_ENV','test')=='test'?1:$price * 100;

        if($user->is_member==1){
            $fee =  ceil( $fee*Constant::DISCOUNT);
        }

        $order = MemberOrder::create(['user_id'=>$user->id,'order_number'=>$order_number,'fee'=>$fee/100,'type'=>$type]);

        $config = config('wechat.default');
        $app = Factory::payment($config);
        $result = $app->order->unify([
            'body' => '池塘边素材-会员充值',
            'out_trade_no' => $order_number,
            'total_fee' => $fee,
            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            'openid' => $user->open_id,
        ]);

        if ($result['return_code'] == 'SUCCESS') {
            $prepay_id = 'prepay_id='.$result['prepay_id'];
            $nonce_str = $result['nonce_str'];
            $appid = $config['app_id'];
            $key = $config['key'];
            $time = time();

            $tmp=[]; //临时数组用于签名
            $tmp['appId'] = $appid;
            $tmp['nonceStr'] = $nonce_str;
            $tmp['package'] = $prepay_id;
            $tmp['signType'] = 'MD5';
            $tmp['timeStamp'] = "$time";

            $data['timeStamp'] = "$time"; //时间戳
            $data['nonceStr'] = $nonce_str; //随机字符串
            $data['signType'] = 'MD5'; //签名算法，暂支持 MD5
            $data['package'] = $prepay_id;
            $data['paySign'] = makeWxSign($tmp, $key);
            $data['out_trade_no'] = $order_number;
            //Log::info('data',$data);
            return responseSuccess($data);
        }else{
            return responseFail('支付失败！');
        }
    }

    public function buyArticle(Request $request) {
        $id = $request->input('id');
        $record = ArticleInfo::where(compact('id'))->first();
        if(empty($record)) return responseFail('未查找到有效文档！');

        $token = $request->header('token');
        $userId = checkJWT($token)['id'];
        $user = User::where(['id'=>$userId])->first();
        if(empty($user)) return responseFail('未查找到有效用户！');

        $order_number = time().uniqid();
        $price = $record->price;
        $fee = env('APP_ENV','test')=='test'?1:$price * 100;
        $order = ArticleOrder::create(['article_id'=>$id,'user_id'=>$user->id,'order_number'=>$order_number,'fee'=>($fee/100)]);

        $config = config('wechat.default');
        $app = Factory::payment($config);
        $result = $app->order->unify([
            'body' => '池塘边素材-文档购买',
            'out_trade_no' => $order_number,
            'total_fee' => $fee,
            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            'openid' => $user->open_id,
            'notify_url'=> env('APP_URL').'/wx/payCallbackForArticle'
        ]);

        if ($result['return_code'] == 'SUCCESS') {
            $prepay_id = 'prepay_id='.$result['prepay_id'];
            $nonce_str = $result['nonce_str'];
            $appid = $config['app_id'];
            $key = $config['key'];
            $time = time();

            $tmp=[]; //临时数组用于签名
            $tmp['appId'] = $appid;
            $tmp['nonceStr'] = $nonce_str;
            $tmp['package'] = $prepay_id;
            $tmp['signType'] = 'MD5';
            $tmp['timeStamp'] = "$time";

            $data['timeStamp'] = "$time"; //时间戳
            $data['nonceStr'] = $nonce_str; //随机字符串
            $data['signType'] = 'MD5'; //签名算法，暂支持 MD5
            $data['package'] = $prepay_id;
            $data['paySign'] = makeWxSign($tmp, $key);
            $data['out_trade_no'] = $order_number;
            //Log::info('data',$data);
            return responseSuccess($data);
        }else{
            return responseFail('支付失败！');
        }


    }


    /*public function getUsers(Request $request) {
        $pageSize = $request->input('pageSize',30);
        $records = User::limit($pageSize)->orderByDesc('id')->get();
        return responseSuccess($records->toArray());
    }

    public function setMember(Request $request) {

    }*/


}
